<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { FormInstance } from 'element-plus';
import { IconSetting } from '@computing/opendesign-icons';
import { getErrorTranslate, traduction } from '@/utils/language';
import { getThreshold, setThreshold } from './threshold.service';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import useStore from '@/stores';
import SecondPassword from '@/components/SecondPassword/SecondPassword.vue';
import { showElMessage } from '@/utils/utils';

const hasUserConfigPrivil = checkPrivil(UserPrivil.diagnosis);
const store = useStore();
let isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});

const thresholdFormRef = ref<FormInstance>();
const thresholdDialogVisible = ref(false);
const secondRef = ref();
const popoverVisible = ref(false);
const thresholdValid = ref(false);
const thresholdForm = reactive<{ threshold: string | null }>({
  threshold: null,
});

const rules = reactive({
  threshold: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === '' || value === null) {
          return callback(new Error(traduction('VALID_REQUIRED_ERR')));
        }
        const numValue = Number(value);
        const invalid =
          isNaN(numValue) ||
          !Number.isInteger(numValue) ||
          numValue < 1 ||
          numValue > 50;
        if (invalid) {
          return callback(new Error(traduction('VALIDTOR_INTGER_RANGE', [1, 50])));
        }
        return callback();
      },
      trigger: 'blur',
    },
  ],
});

function validateForm() {
  popoverVisible.value = false;
  if (!thresholdFormRef.value) {
    return;
  }
  thresholdFormRef.value.validate((valid: boolean) => {
    thresholdValid.value = valid;
  });
}

async function saveBtnClick(): Promise<void> {
  if (thresholdForm.threshold === null) {
    return;
  }
  try {
    await setThreshold(parseInt(thresholdForm.threshold, 10));
    showElMessage('success', traduction('COMMON_SUCCESS'));
  } catch (e: any) {
    showElMessage('error', getErrorTranslate(e.data?.error?.[0]?.code ?? 'COMMON_FAILED'));
  } finally {
    thresholdDialogVisible.value = false;
    thresholdForm.threshold = `${await getThreshold()}`;
  }
}

function closeSecondPwd(res: { reason: boolean; password: string }) {
  if (res.reason) {
    secondRef.value.hide();
  } else {
    secondRef.value.hide();
  }
}

function handleKeyDown(event: KeyboardEvent): void {
  if (['-', '.'].some(item => event.key === item)) {
    event.preventDefault();
  }
}

onMounted(async () => {
  thresholdForm.threshold = `${await getThreshold()}`;
});
</script>

<template>
  <el-button
    v-if="hasUserConfigPrivil"
    :disabled="isSystemLock"
    class="advanced-settings"
    @click="thresholdDialogVisible = true"
  >
    <el-icon :size="16"><IconSetting /></el-icon>
    {{ $t('ADVANCED_SETTINGS') }}
  </el-button>
  <el-dialog
    v-model="thresholdDialogVisible"
    class="ssdThreshold"
    :title="$t('WEAR_RATE_THRESHOLD_SETTING')"
    width="432px"
  >
    <el-alert type="info" :closable="false" show-icon>{{ $t('WEAR_RATE_TIP') }}</el-alert>
    <div class="thresholdForm">
      <el-form ref="thresholdFormRef" :model="thresholdForm" :rules="rules" label-width="auto">
        <el-form-item :label="$t('WEAR_RATE_LABEL')" prop="threshold">
          <el-popover :visible="popoverVisible" :content="$t('VALIDTOR_INTGER_RANGE', [1, 50])" placement="right">
            <template #reference>
              <el-input
                v-model="thresholdForm.threshold"
                type="number"
                @keydown="handleKeyDown"
                @input="validateForm"
                @focus="popoverVisible = true"
                @blur="popoverVisible = false"
              ></el-input>
            </template>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button
        :disabled="!thresholdValid"
        type="primary"
        @click="saveBtnClick"
      >
        {{ $t('COMMON_SAVE') }}
      </el-button>
      <el-button @click="thresholdDialogVisible = false">{{ $t('ALARM_CANCEL') }}</el-button>
    </template>
  </el-dialog>
  <SecondPassword ref="secondRef" @close="closeSecondPwd"></SecondPassword>
</template>

<style lang="scss" scoped>
.advanced-settings {
  position: absolute;
  right: 24px;
  top: -40px;
}
.thresholdForm {
  margin-top: 16px;
}
</style>
